using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using BSDS.Core.Model.Data;

namespace BSDS.Core.Data.Local.Xml.Parsing
{
    public class XmlAttributeParser
    {

        public AttributeInfo[] FromXml(XElement schemaNode, string xsns = "http://www.w3.org/2001/XMLSchema")
        {
            var primaryKeyName = GetPrimaryKeyName(schemaNode, xsns);

            var attributeInfos = new List<AttributeInfo>();

            var childNodes = schemaNode.Descendants(XName.Get("element", xsns)).Skip(2);  

            foreach (var childNode in childNodes)
            {
                var name = childNode.Attributes(XName.Get("name")).First().Value;
                var type = childNode.Attributes(XName.Get("type")).First().Value.Split(':')[1];

                attributeInfos.Add(new AttributeInfo(name, type, name == primaryKeyName));
            }

            return attributeInfos.ToArray();
        }

        private static string GetPrimaryKeyName(XElement schemaNode, string xsns)
        {
            var primaryKeyNode = schemaNode.Descendants(XName.Get("field", xsns)).Attributes("xpath").FirstOrDefault();

            if(primaryKeyNode != null)
            {
                return primaryKeyNode.Value;
            }
           
            throw new ArgumentException("No primary key information found.");
        }
    }
}